<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\OeVideoCoverModel;
use app\model\OeVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class VideoCoverService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['video_cover'];

    /**
     * 获取视频封面.
     *
     * @param string $advertiserId 广告主id
     */
    public static function getVideoCover(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $account = explode('_', $advertiserId);
            if (count($account) > 1) {
                // 指定视频拉取封面
                $advertiserId = $account[0];
                $videos = [$account[1]];
            } else {
                $videos = self::getVideos($advertiserId);
            }
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            if ($videos) {
                foreach ($videos as $videoId) {
                    // 判断是否已有封面
                    if (self::getInfo($advertiserId, $videoId)) {
                        continue;
                    }
                    $result = self::getList($advertiserId, $videoId);
                    if ($result === false) {
                        return false;
                    }
                    if ($result['data']['status'] != 'SUCCESS') {
                        continue;
                    }
                    if (count($result['data']['list']) == 0) {
                        continue;
                    }
                    foreach ($result['data']['list'] as $item) {
                        $model = new OeVideoCoverModel();
                        $item['cover_id'] = $item['id'];
                        $item['advertiser_id'] = $advertiserId;
                        $item['video_id'] = $videoId;
                        unset($item['id']);
                        $model->setAttrs($item);
                        if (! $model->save()) {
                            throw new \Exception('保存信息出错');
                        }
                    }

                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取信息.
     *
     * @param string $advertiserId 账户id
     * @param string $videoId 视频id
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', string $videoId = '')
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'video_id' => $videoId,
        ];

        return AdvertiserService::getVideoCover($headers, $params);
    }

    /**
     * 获取视频封面信息.
     *
     * @param string $advertiserId 账户id
     * @param string $videoId 视频id
     * @return null|array|mixed|Model|OeVideoModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', string $videoId = '')
    {
        $where = [
            ['video_id', '=', $videoId],
            ['advertiser_id', '=', $advertiserId],
        ];

        return (new OeVideoCoverModel())->where($where)->field(true)->find();
    }

    /**
     * 获取视频信息.
     *
     * @param string $advertiserId 账户id
     */
    private static function getVideos(string $advertiserId = ''): array
    {
        return (new OeVideoModel())->where('advertiser_id', $advertiserId)->field(true)->column('video_id');
    }
}
